package com.straw.hat.shardingjdbc.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.LocalDateTimeTypeHandler;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @company: 鲸灵科技
 * @author: qiyue@webuy.ai
 * @date: 2019/10/7
 * @time: 2:57 下午
 */
@Configuration
@ConditionalOnBean(DataSourceConfig.class)
@MapperScan(basePackages = "com.straw.hat.shardingjdbc.dao")
public class MybatisConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(){
        SqlSessionFactory sqlSessionFactory = null;
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            //添加插件
            PageInterceptor pageInterceptor = new PageInterceptor();
            Properties props = new Properties();
            props.setProperty("reasonable", "true");
            props.setProperty("supportMethodsArguments", "true");
            props.setProperty("returnPageInfo", "check");
            props.setProperty("params", "count=countSql");
            pageInterceptor.setProperties(props);
            Interceptor [] interceptors = new Interceptor[] {pageInterceptor};
            bean.setPlugins(interceptors);

            /*添加TypeHandle*/
            LocalDateTimeTypeHandler localDateTimeTypeHandler = new LocalDateTimeTypeHandler();
            TypeHandler [] typeHandlers = new TypeHandler[]{localDateTimeTypeHandler};
            bean.setTypeHandlers(typeHandlers);

            /*设置mapper路径*/
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            sqlSessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }

}
